<?php
	session_start();
	if(session_is_registered(username)){
		$name=$_SESSION['username'];
	}
	else{
		//nao e preciso estar logged in
		$name="guest";
	}
	try{
		$db = new PDO('sqlite:../../projecto1.db');
	}
	catch(PDOException $err){
		if($xml==0){
			$error['Result'] = array('Popular'=>'DatabaseError');
			echo json_encode($error);
			die;
		}else{
			$doc = new DomDocument('1.0');
			$doc->formatOutput = TRUE;
			// create root node
			$root = $doc->createElement('Result');
			$root = $doc->appendChild($root);
			$attr = $doc->createAttribute("xmlns:xsi");
			$attr->value = "http://www.w3.org/2001/XMLSchema-instance";
			$root->appendChild($attr);
			$attr = $doc->createAttribute("xsi:noNamespaceSchemaLocation");
			$attr->value = "http://gnomo.fe.up.pt/~ei10048/trabalho2/xsd.xsd";
			$root->appendChild($attr);
			//childs of root
			$error = $doc->createElement('Popular');
			$error= $root->appendChild($error);
			$value = $doc->createTextNode('DatabaseError');
			$value = $error->appendChild($value);
			echo $doc->saveXML();
		}
	}
	if(isset($_REQUEST['verbose']) && ($_REQUEST['verbose'] == '1')){
		$verbose=1;
	}else{$verbose=0;}
	if(isset($_REQUEST['xml']) && ($_REQUEST['xml'] == '1')){
		$xml=1;
	}else{$xml=0;}
	
	if(isset($_REQUEST['numero']) && $_REQUEST['numero'] != ""){
		$numero=$_REQUEST['numero'];
	}else{
		$numero =5;
	}
	
	$stmt = $db->prepare('SELECT * FROM Link ORDER BY hits desc');	
	$stmt->execute();
	$link_list = $stmt->fetchAll();
	
	foreach($link_list as $link){
		$stmt = $db->prepare('SELECT * FROM User_Link where idLink=:idLink');
		$stmt->bindParam(':idLink', $link['idLink']);
		$stmt->execute();
		$link_info[] = $stmt->fetchAll();
	}
	
	/*foreach($link_info as $user_links){
		foreach($user_links as $user_link){
						
		}
	}*/
	
	
	$contador=0;
	foreach ($link_list as $link1) {
		foreach ($link_info as $link2) {
			foreach ($link2 as $link3) {
				if($contador < $numero){
					if($link1['idLink'] == $link3['idLink']){
						$json['Result']['Popular'][$contador] = array('title'=>$link3['title'],
						'linkURL'=>$link1['linkURL'],'description'=>$link3['description'],'hits'=>$link1['hits']);
						$posicaoarray=0;
						
						$stmt = $db->prepare('SELECT * FROM User_Link_Tag WHERE User_Link_Tag.idUserLink=:iduserlink');
						$stmt->bindParam(':iduserlink', $link3['idUserLink']);
						$stmt->execute();
						$tags = $stmt->fetchAll();
						if(!$tags){
							$tags = array();
						}
						
						if(!$tags){
							$array = array();
						}else{
							$array = array();
							foreach ($tags as $tag){
								$stmt = $db->prepare('SELECT * FROM Tag WHERE Tag.idTag=:idTag');
								$idTag = $tag['idTag'];
								$stmt->bindParam(':idTag', $idTag);
								$stmt->execute();
								$tag_name = $stmt->fetch();
								$array[$posicaoarray]=$tag_name['tagName'];
								$posicaoarray++;
							}
						}
						$json['Result']['Popular'][$contador]['tags']=$array;
						$contador++;
					}
				}
			}	
		}
	}

	if($xml==0){
		echo json_encode($json);
		die;
	}else{
		$doc = new DomDocument('1.0');
		$doc->formatOutput = TRUE;
		// create root node
		$root = $doc->createElement('Result');
		$root = $doc->appendChild($root);
		$attr = $doc->createAttribute("xmlns:xsi");
		$attr->value = "http://www.w3.org/2001/XMLSchema-instance";
		$root->appendChild($attr);
		$attr = $doc->createAttribute("xsi:noNamespaceSchemaLocation");
		$attr->value = "http://gnomo.fe.up.pt/~ei10048/trabalho2/xsd.xsd";
		$root->appendChild($attr);
		$popular = $doc->createElement('Popular');
		$error= $root->appendChild($popular);
		//childs of root
		foreach($json as $j){
			foreach($j as $k){
				foreach($k as $l){
					$link = $doc->createElement('Link');
					$error= $popular->appendChild($link);
					
					$link_url = $doc->createElement('Title');
					$error= $link->appendChild($link_url);
					$value = $doc->createTextNode($l['title']);
					//if($verbose ==1){echo $value;echo'<br />';}
					$value = $error->appendChild($value);
					
					$link_url = $doc->createElement('LinkURL');
					$error= $link->appendChild($link_url);
					$value = $doc->createTextNode($l['linkURL']);
					//if($verbose ==1){echo $value;echo'<br />';}
					$value = $error->appendChild($value);
					
					$link_url = $doc->createElement('Description');
					$error= $link->appendChild($link_url);
					$value = $doc->createTextNode($l['description']);
					//if($verbose ==1){echo $value;echo'<br />';}
					$value = $error->appendChild($value);
							
					$link_hits = $doc->createElement('Hits');
					$error= $link->appendChild($link_hits);
					$value = $doc->createTextNode($l['hits']);
					//if($verbose ==1){echo $value;echo'<br />';}
					$value = $error->appendChild($value);
					
					$tags = $doc->createElement('Tags');
					$error= $link->appendChild($tags); 
					foreach($l['tags'] as $m){
						$link_tags = $doc->createElement('Tag');
						$error= $tags->appendChild($link_tags);
						$value = $doc->createTextNode($m);
						//if($verbose ==1){echo $value;echo'<br />';}
						$value = $error->appendChild($value);
					}
				}
			}
		}
		echo $doc->saveXML();
		die;
	}	
?>